import 'dart:convert';

import '../util/MyCircularCheckBox.dart';
// import 'package:circular_check_box/circular_check_box.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import '../util/Toast.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../base/Constant.dart';
// import 'package:panda/base/SignType.dart';
import '../entity/shop_car_entity.dart';
import 'package:flutter_aygsh/http/HttpUtil.dart';
import 'package:flutter_aygsh/http/Api.dart';
import '../liz_mine/order/OrderPage.dart';
import '../util/AppSaveInfoUtil.dart';
import '../util/SignUtil.dart';
import 'BuyGoodsByCar.dart';
import '../event/LoginEvent.dart';
import '../base/application.dart';

class MyShopCarPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyShopCarFragmentState();
  }
}

class MyShopCarFragmentState extends State<MyShopCarPage>
    with WidgetsBindingObserver {
  final SlidableController slidableController = SlidableController();

  EasyRefreshController _controller = new EasyRefreshController();
  int currentStatus = 0;
  bool isSelectAll = false;
  double total = 0;
  String token = "";
  List<MyShopCarDataData> dataList = new List();
  int loginStatusCode = 0;

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(
          "购物车",
          style: TextStyle(
              fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
              color: Colors.black),
        ),
        elevation: 0.5,
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
        actions: <Widget>[
          GestureDetector(
            child: Container(
              alignment: Alignment.center,
              padding: EdgeInsets.fromLTRB(0, 0, 13, 0),
              child: Text(
                currentStatus == 0 ? '管理' : '完成',
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                    color: Colors.black54),
              ),
            ),
            onTap: () {
              if (currentStatus == 0) {
                currentStatus = 1;
                setState(() {});
              } else {
                currentStatus = 0;
                setState(() {});
              }
            },
          )
        ],
      ),
      body: AnnotatedRegion<SystemUiOverlayStyle>(
        child: loginStatusCode == 4
            ? Container(
                alignment: Alignment.center,
                // width: ScreenUtil.getInstance().setWidth(550.00),
                // height: ScreenUtil.getInstance().setWidth(DP_90),
                // margin: EdgeInsets.fromLTRB(
                //     0, ScreenUtil.getInstance().setWidth(DP_90), 0, 0),
                child: Container(
                  decoration: new BoxDecoration(
                    color:Color.fromARGB(255, 255, 140, 16),
                      borderRadius: BorderRadius.circular(
                          ScreenUtil.getInstance().setHeight(DP_80))),
                  child: new FlatButton(
                    child: new Padding(
                      padding: EdgeInsets.all(0.0),
                      child: new Text(
                        "请先登录",
                        style: new TextStyle(
                            color: Colors.white,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE)),
                      ),
                    ),
                    onPressed: () {
                      Navigator.of(context).pushNamed('login');
                    },
                  ),
                ))
            : dataList.length > 0
                ? Column(
                    children: <Widget>[
                      Expanded(
                        child: new EasyRefresh(
                          controller: _controller,
                          header: MaterialHeader(),
                          footer: MaterialFooter(),
                          enableControlFinishLoad: false,
                          enableControlFinishRefresh: true,
                          child: ListView.builder(
                            itemCount: dataList.length,
                            itemBuilder: (BuildContext context, int index) {
                              return renderView(context, index);
                            },
                          ),
                          onRefresh: () {
                            currentStatus = 0;
                            isSelectAll = false;
                            getString(TOKEN).then((value) {
                              token = value;
                              loadList();
                            });
                          },
                        ),
                      ),
                      Container(
                        height: 0.5,
                        color: f0Color,
                      ),
                      Container(
                        color: white,
                        padding: EdgeInsets.fromLTRB(
                            ScreenUtil.getInstance().setHeight(5),
                            ScreenUtil.getInstance().setHeight(DP_10),
                            ScreenUtil.getInstance().setHeight(DP_20),
                            ScreenUtil.getInstance().setHeight(DP_10)),
                        child: Row(
                          children: <Widget>[
                            MyCircularCheckBox(
                                value: isSelectAll,
                                activeColor: mainColor,
                                inactiveColor: black_99,
                                materialTapTargetSize:
                                    MaterialTapTargetSize.padded,
                                onChanged: (bool x) {
                                  isSelectAll = !isSelectAll;
                                  checkAll();
                                  setState(() {});
                                }),
                            Text('全选',
                                style: TextStyle(
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(SMALL_FONT_SIZE),
                                    color: Colors.black87)),
                            Container(
                              width: 15,
                            ),
                            Expanded(
                              child: Text(
                                  currentStatus == 0
                                      ? '合计：' + (MONEY + '$total')
                                      : '',
                                  style: TextStyle(
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(NORMAL_FONT_SIZE),
                                      color: Colors.black87)),
                              // Text(currentStatus == 0 ? (MONEY + '$total') : '',
                              //     style: TextStyle(
                              //         fontSize: ScreenUtil.getInstance()
                              //             .setSp(BIG_FONT_SIZE),
                              //         color: Colors.black87)),
                            ),
                            Expanded(
                              child: Text(''),
                            ),
                            new Container(
                              height: ScreenUtil.getInstance().setHeight(DP_60),
                              decoration: new BoxDecoration(
                                  // color: Colors.red,
                                  image: DecorationImage(
                                      image:
                                          AssetImage("images/qianggou_bg.png"),
                                      fit: BoxFit.fill),
                                  borderRadius: BorderRadius.circular(
                                      ScreenUtil.getInstance()
                                              .setHeight(DP_60) /
                                          2)),
                              padding: EdgeInsets.fromLTRB(5.0, 0.0, 5.0, 0.0),
                              child: new FlatButton(
                                child: new Container(
                                  padding: EdgeInsets.all(0.0),
                                  child: new Text(
                                    currentStatus == 0 ? "去结算" : '删除',
                                    style: new TextStyle(
                                        color: Colors.white,
                                        fontSize: ScreenUtil.getInstance()
                                            .setSp(NORMAL_FONT_SIZE),
                                        fontWeight: FontWeight.w400),
                                  ),
                                ),
                                onPressed: () {
                                  if (currentStatus == 0) {
                                    List<MyShopCarDataData> temp = new List();
                                    for (int i = 0; i < dataList.length; i++) {
                                      if (dataList[i].isSelect) {
                                        temp.add(dataList[i]);
                                      }
                                    }
                                    if(temp.length==0){
                                      Toast.toast(context,msg:'请选择要购买的商品');
                                      return;
                                    }
                                    Navigator.of(context).push<String>(
                                        MaterialPageRoute(builder: (context) {
                                      return new BuyGoodsByCarPage(
                                        datas: temp,
                                        total: total.toString(),
                                      );
                                    })).then((value) {
                                      
                                      if (value != null) {
                                        currentStatus = 0;
                                        isSelectAll = false;
                                        loadList();
                                        if(value=='购物车'){
                                          return;
                                        }
                                        Navigator.of(context).push(
                                            MaterialPageRoute(
                                                builder: (context) {
                                          return new OrderPage();
                                        }));
                                      }
                                      
                                    });
                                  } else {
                                    //多选删除
                                    List temp = new List();
                                    for (int i = 0; i < dataList.length; i++) {
                                      if (dataList[i].isSelect) {
                                        temp.add(dataList[i].id);
                                      }
                                    }
                                    String str = '';
                                    temp.forEach((f) {
                                      if (str == '') {
                                        str = "$f";
                                      } else {
                                        str = "$str" "," "$f";
                                      }
                                    });
                                    manyDel(str);
                                  }
                                },
                              ),
                            )
                          ],
                        ),
                      ),
                    ],
                  )
                : Container(
                    alignment: Alignment.center,
                    child: Column(
                      children: <Widget>[
                        Container(
                          margin: EdgeInsets.only(
                              top: ScreenUtil.getInstance().setHeight(300)),
                        ),
                        Container(
                          alignment: Alignment.center,
                          child: Text('购物袋空空如也～'),
                        ),
                        Container(
                          margin: EdgeInsets.only(
                              top: ScreenUtil.getInstance().setHeight(50)),
                        ),
                        Container(
                          padding: EdgeInsets.fromLTRB(
                              ScreenUtil.getInstance().setWidth(25),
                              ScreenUtil.getInstance().setWidth(15),
                              ScreenUtil.getInstance().setWidth(25),
                              ScreenUtil.getInstance().setWidth(15)),
                          decoration: new BoxDecoration(
                            color: Color.fromARGB(255, 255, 140, 16),
                              borderRadius: BorderRadius.circular(
                                  ScreenUtil.getInstance().setHeight(DP_80))),
                          child:
                              // new FlatButton(
                              //   child: new Padding(
                              //     padding: EdgeInsets.all(0.0),
                              new Text(
                            "去逛逛",
                            style: new TextStyle(
                                color: Colors.white,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(NORMAL_FONT_SIZE)),
                          ),
                          //   ),
                          //   onPressed: () {

                          //   },
                          // ),
                        )
                      ],
                    )),
        value: SystemUiOverlayStyle.dark,
      ),
    );
  }

  Widget renderView(BuildContext context, int index) {
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil.getInstance().setHeight(DP_15),
          ScreenUtil.getInstance().setHeight(DP_15),
          ScreenUtil.getInstance().setHeight(DP_15),
          0),
      decoration: BoxDecoration(
          color: white,
          borderRadius:
              BorderRadius.circular(ScreenUtil.getInstance().setHeight(DP_10))),
      child: Slidable(
        actionPane: SlidableStrechActionPane(),
        controller: slidableController,
        actionExtentRatio: 0.25,
        secondaryActions: <Widget>[
          IconSlideAction(
            caption: '删除',
            color: Colors.red,
            icon: Icons.delete,
            closeOnTap: true,
            onTap: () {
              print('删除');
              del(index);
            },
          ),
        ],
        child: Padding(
          padding: EdgeInsets.fromLTRB(
              ScreenUtil.getInstance().setHeight(0),
              ScreenUtil.getInstance().setHeight(DP_20),
              ScreenUtil.getInstance().setHeight(DP_20),
              ScreenUtil.getInstance().setHeight(DP_20)),
          child: new Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              MyCircularCheckBox(
                  value: dataList[index].isSelect,
                  activeColor: mainColor,
                  inactiveColor: black_99,
                  materialTapTargetSize: MaterialTapTargetSize.padded,
                  onChanged: (bool x) {
                    dataList[index].isSelect = !dataList[index].isSelect;
                    change();
                    setState(() {});
                  }),
              ClipRRect(
                  borderRadius: BorderRadius.circular(5),
                  child: CachedNetworkImage(
                    width: ScreenUtil.getInstance().setHeight(DP_120),
                    fit: BoxFit.fill,
                    height: ScreenUtil.getInstance().setHeight(DP_120),
                    imageUrl: Api.ImgBaseUrl + dataList[index].img,
                    placeholder: (context, url) => Image.asset(
                        'images/pic_default.png',
                        width: ScreenUtil.getInstance().setHeight(DP_120),
                        fit: BoxFit.fill,
                        height: ScreenUtil.getInstance().setHeight(DP_120)),
                    errorWidget: (context, url, error) => Image.asset(
                        'images/pic_default.png',
                        width: ScreenUtil.getInstance().setHeight(DP_120),
                        fit: BoxFit.fill,
                        height: ScreenUtil.getInstance().setHeight(DP_120)),
                  )),
              Container(
                width: ScreenUtil.getInstance().setHeight(DP_15),
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(dataList[index].goods_name,
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: Colors.black87)),
                    Container(
                      height: ScreenUtil.getInstance().setHeight(DP_10),
                    ),
                    Text(dataList[index].sku_str,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize:
                                ScreenUtil.getInstance().setSp(MINI_FONT_SIZE),
                            color: Colors.black38)),
                    Container(
                      height: ScreenUtil.getInstance().setHeight(DP_10),
                    ),
                    Row(
                      children: <Widget>[
                        Expanded(
                          child: Text(MONEY + dataList[index].price,
                              maxLines: 1,
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(BIG_FONT_SIZE),
                                  color: mainColor)),
                        ),
                        GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            if (dataList[index].goods_num == "1") {
                              return;
                            }
                            dataList[index].goods_num =
                                (int.parse(dataList[index].goods_num) - 1)
                                    .toString();
                            change();
                            setState(() {});
                          },
                          child: Icon(
                            Icons.remove,
                            size: ScreenUtil.getInstance().setHeight(DP_30),
                            color: black,
                          ),
                        ),
                        Container(
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(2),
                              color: f0Color),
                          padding: EdgeInsets.fromLTRB(
                              ScreenUtil.getInstance().setHeight(DP_20),
                              2,
                              ScreenUtil.getInstance().setHeight(DP_20),
                              2),
                          margin: EdgeInsets.fromLTRB(
                              ScreenUtil.getInstance().setHeight(DP_10),
                              0,
                              ScreenUtil.getInstance().setHeight(DP_10),
                              0),
                          child: Text(
                            dataList[index].goods_num,
                            style: TextStyle(
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE),
                                color: Colors.black87),
                          ),
                        ),
                        GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            dataList[index].goods_num =
                                (int.parse(dataList[index].goods_num) + 1)
                                    .toString();
                            change();
                            setState(() {});
                          },
                          child: Icon(
                            Icons.add,
                            size: ScreenUtil.getInstance().setHeight(DP_30),
                            color: black,
                          ),
                        ),
                      ],
                    )
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) {
      if (!ModalRoute.of(context).isCurrent) {
        return;
      }
    }
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    getString(TOKEN).then((value) {
      if (value == null) {
        return;
      }
      token = value;
      loadList();
    });
    APPLIC.eventBus.on<LoginEvent>().listen((event) {
      getString(TOKEN).then((value) {
        if (value == null) {
          return;
        }
        token = value;
        loadList();
        total = 0;
      });
    });
  }

  loadList() async {
    Map map = new Map.from({
      "token": token,
      "sign_type": createSignType(Api.URL_SHOPCART_LIST),
    });
    Response<String> response =
        await HttpUtil().post(Api.URL_SHOPCART_LIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    // print('购物车');
    print(response);
    setState(() {
      loginStatusCode = userMap['code'];
    });
    if (userMap['code'] != 1) {
      // Fluttertoast.showToast(msg: userMap['msg']);
      Toast.toast(context,msg: userMap['msg']);
      // if (userMap['code'] == 106) {
      //   Navigator.of(context).pushNamed('login');
      // }
      return;
    }
    MyShopCarEntity homeListEntity = new MyShopCarEntity.fromJson(userMap);
    if (userMap['code'] == 1 && mounted) {
      setState(() {
        dataList.clear();
        _controller.finishRefresh();
        dataList.addAll(homeListEntity.data.datas);
      });
    }
  }

  del(int pos) async {
    Map map = new Map();
    map['token'] = token;
    map['goods_id'] = dataList[pos].goods_id;
    map['sign_type'] = createSignType(Api.URL_SHOPCART_DEL);
    Response<String> response =
        await HttpUtil().post(Api.URL_SHOPCART_DEL, data: getSign(map));
    Map userMap = json.decode(response.data);
    print(userMap);
    int code = userMap['code'];
    if (code == 1) {
      dataList.removeAt(pos);
      // change();
      loadList();
      setState(() {
        total = 0;
      });
    } else {
      // Fluttertoast.showToast(msg: userMap['msg']);
       Toast.toast(context,msg: userMap['msg']);
      userMap = null;
    }
  }

  manyDel(String ids) async {
    Map map = new Map();
    map['token'] = token;
    map['id'] = ids;
    map['sign_type'] = createSignType(Api.URL_Many_SHOPCART_DEL);
    Response<String> response =
        await HttpUtil().post(Api.URL_Many_SHOPCART_DEL, data: getSign(map));
    Map userMap = json.decode(response.data);
    print(userMap);
    int code = userMap['code'];
    if (code == 1) {
      // List arrs = ids.split(',');
      // for (String id in arrs) {
      //   dataList.removeAt(int.parse(id));
      // }
      // change();
      loadList();
      setState(() {
        total = 0;
      });
    } else { 
      Toast.toast(context,msg: userMap['msg']);
      userMap = null;
    }
  }

  change() {
    total = 0.00;
    for (int i = 0; i < dataList.length; i++) {
      if (dataList[i].isSelect) {
        total = total +
            double.parse(dataList[i].goods_num) * double.parse(dataList[i].price);
      }
    }
    total = double.parse(formatNum(total, 2));
  }

  String formatNum(double num, int postion) {
    if ((num.toString().length - num.toString().lastIndexOf(".") - 1) <
        postion) {
      return num.toStringAsFixed(postion)
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    } else {
      return num.toString()
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    }
  }

  checkAll() {
    for (int i = 0; i < dataList.length; i++) {
      dataList[i].isSelect = isSelectAll;
    }
    change();
    setState(() {});
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this); //销毁观察者
  }

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) {
    return false;
  }
}

class BuGoodsByCarPage {}
